<template>
  <el-dialog
    v-model="visible"
    width="560px"
    class="restock-dialog"
    title="📦 补充库存"
    :close-on-click-modal="false"
    @closed="resetForm"
  >
    <!-- 商品信息卡片 -->
    <el-card shadow="never" class="stock-card">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="商品名称">
          <strong>{{ productName }}</strong>
        </el-descriptions-item>

        <el-descriptions-item label="当前库存">
          <el-tag type="info" size="large">{{ currentStock }}</el-tag>
        </el-descriptions-item>

        <el-descriptions-item label="补货后库存">
          <el-tag :type="addStock > 0 ? 'success' : 'info'" size="large">
            {{ newStock }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 补货表单 -->
    <section class="restock-section">
      <div class="section-header">补货信息</div>
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="90px">
        <el-form-item label="补货数量" prop="addStock">
          <el-input-number
            v-model="formData.addStock"
            :min="1"
            :max="99999"
            controls-position="right"
            style="width: 100%"
            placeholder="请输入补货数量"
          />
        </el-form-item>
      </el-form>
    </section>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="hide">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">
          确认补货
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { addProductStock } from '@/api/goods';

interface Product {
  productId?: number;
  productName?: string;
  stock?: number;
}

const visible = ref(false);
const submitLoading = ref(false);
const formRef = ref();
const emits = defineEmits(['ok']);
const product = ref<Product>({});

const formData = reactive({
  addStock: 0
});

// === 计算属性：抽离模板逻辑 ===
const productName = computed(() => product.value.productName || '—');
const currentStock = computed(() => {
  const stock = product.value.stock;
  const num = Number(stock);
  return isNaN(num) ? 0 : num;
});

const addStock = computed(() => {
  const val = formData.addStock;
  const num = Number(val);
  return isNaN(num) || num < 0 ? 0 : Math.floor(num);
});

const newStock = computed(() => currentStock.value + addStock.value);

const rules = {
  addStock: [
    { required: true, message: '请输入补货数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于 0', trigger: 'blur' }
  ]
};

const show = (data?: Product) => {
  if (data) product.value = data;
  visible.value = true;
  nextTick(() => {
    formData.addStock = 0;
  });
};

const hide = () => (visible.value = false);

const resetForm = () => {
  formRef.value?.resetFields();
  formData.addStock = 0;
};

const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return;
    submitLoading.value = true;

    try {
      const res = await addProductStock({
        productId: product.value.productId,
        stock: formData.addStock
      });

      if (res.code === 200) {
        ElMessage.success('✅ 补货成功');
        emits('ok');
        hide();
      } else {
        ElMessage.error(res.msg || '补货失败');
      }
    } catch (e) {
      ElMessage.error('请求异常，请稍后重试');
    } finally {
      submitLoading.value = false;
    }
  });
};

defineExpose({ show });
</script>

<style scoped lang="scss">
.restock-dialog {
  :deep(.el-dialog__header) {
    padding: 20px 24px 12px;
  }

  :deep(.el-dialog__body) {
    padding: 16px 24px;
  }

  :deep(.el-dialog__footer) {
    padding: 0 24px 20px;
  }
}

.stock-card {
  margin-bottom: 24px;
  border-radius: 12px;
  background-color: #fafafa;
  border: none;
}

.restock-section {
  background: #ffffff;
  border: 1px solid #eee;
  border-radius: 12px;
  padding: 18px 20px 12px;

  .section-header {
    font-weight: 600;
    font-size: 14px;
    margin-bottom: 14px;
    padding-left: 8px;
    border-left: 2px solid var(--el-color-primary);
    color: #333;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 8px;
}
</style>
